import React, { useContext, useState } from 'react';
import { Typography } from 'antd';
import { useRequest } from 'ahooks';
import moment from 'moment';
import { connect } from 'dva';
import Tabs from '@/components/MarketingMap/Tabs';
import LineChart from '@/components/MarketingMap/LineChart';
import DateFrom from '@/components/MarketingMap/DateFrom';
import TabelLoadMore from '@/components/MarketingMap/TabelLoadMore';
import EmptyState from '@/components/MarketingMap/EmptyState';
import { fetchInflowStoreTrend } from '@/services/marketingMap/inflowAnalysis';
import usePermissionCheck from '@/hooks/usePermissionCheck';
import { formatValue, formatDate } from '@/utils/marketingMap/utils';
import styles from '../styles/panel.less';
import OverallContext from '../context';
import TipMessage from '@/components/MarketingMap/TipMessage';

const columns = [
  {
    title: '排名',
    dataIndex: 'rank',
  },
  {
    title: '售后店',
    dataIndex: 'name',
    render: (text: string) => (
      <Typography.Text style={{ width: 150 }} ellipsis={{ tooltip: text }}>
        {text}
      </Typography.Text>
    ),
  },
  {
    title: '距离',
    dataIndex: 'distance',
    render: (text: number) => formatValue(text, 'km'),
  },
  {
    title: <TipMessage name="流入车辆">流入保客</TipMessage>,
    className: styles.white_space,
    width: 60,
    dataIndex: 'vehicleCount',
  },
  {
    title: '占比',
    dataIndex: 'percent',
    render: (text: number) => formatValue(text, '%'),
  },
  {
    title: <TipMessage name="流入客次">流入客次</TipMessage>,
    className: styles.white_space,
    width: 60,
    dataIndex: 'timeCount',
  },
  {
    title: <TipMessage name="总流入客次">总流入客次</TipMessage>,
    className: styles.white_space,
    width: 80,
    dataIndex: 'totalTimeCount',
  },
];

const LineCard: React.FC = () => {
  const { query, date } = useContext(OverallContext);
  const [trend, setTrend] = useState(0);
  const { data, run, loading } = useRequest(() => fetchInflowStoreTrend({ ...query, trend }), {
    refreshDeps: [query, trend],
    refreshDepsAction: () => {
      if (!query.store) {
        return;
      }
      run();
    },
  });

  return (
    <div>
      <Typography className={styles.title}>
        <Typography.Text strong>流入趋势图</Typography.Text>
      </Typography>
      <span>
        统计时间：
        {moment(date.summaryDate).subtract(date.timeRange, 'month')?.format('YYYY-MM-DD')} ~{' '}
        {date.summaryDate}
      </span>
      <Tabs value={trend} onChange={setTrend} tabs={['日趋势', '周趋势', '月趋势']} />

      <EmptyState empty={!data?.length} loading={loading}>
        <LineChart
          xAxis={data?.map((item: { date: string }) =>
            trend === 2 ? formatDate(item.date, 'year') : formatDate(item.date),
          )}
          name="流入车辆（台）"
          series={[
            {
              name: '流入',
              data: data?.map((item: { date: string; vehicleCount: string }) => ({
                name: item.date,
                value: item.vehicleCount,
              })),
              type: 'line',
              smooth: true,
            },
          ]}
        />
      </EmptyState>
    </div>
  );
};

const StatisticsOverview: React.FC<any> = ({ permissions, overviewData, rankData }) => {
  const { codeNameMap, date, onSubmit } = useContext(OverallContext);
  const [isAuth] = usePermissionCheck(permissions, 'inflow-screen');

  return (
    <div className={styles.sidenar_wrapper}>
      <DateFrom value={date} onChange={onSubmit} />
        <div>
          <Typography className={styles.title}>
            <Typography.Text strong>
              {isAuth ? `了解${codeNameMap.store}流入情况` : '了解我的店铺流入情况'}
            </Typography.Text>
          </Typography>
          <div className={styles.box} style={{ padding: '0 24px' }}>
            <div className={styles.item}>
              <div>
                <span style={{ fontSize: 20, color: '#000' }}>{formatValue(overviewData?.vehicleCount)}</span>{' '}
                台
              </div>
              <TipMessage name="流入车辆/流入保客">
                <span>流入车辆</span>
              </TipMessage>
            </div>
            <div className={styles.item}>
              <div>
                <span style={{ fontSize: 20, color: '#000' }}>{formatValue(overviewData?.timeCount)}</span> 次
              </div>
              <TipMessage name="流入车次/流入客次">
                <span>流入车次</span>
              </TipMessage>
            </div>
            <div className={styles.item}>
              <div>
                <span style={{ fontSize: 20, color: '#000' }}>{formatValue(overviewData?.rank)}</span>
              </div>
              <span>大区流入排名</span>
            </div>
          </div>
        </div>
      <LineCard />
      <div>
        <Typography className={styles.title}>
          <Typography.Text strong>吸纳了哪些店铺的客户</Typography.Text>
        </Typography>
        <TabelLoadMore
          columns={columns}
          dataSource={rankData}
          rowKey="code"
        />
      </div>
    </div>
  );
};

export default connect(({ menu }: any) => ({ permissions: menu.permissions }))(StatisticsOverview);
